#!/usr/bin/python

import sys
import gtk
from pysqlite2 import dbapi2 as sqlite3
from datetime import datetime

from nMedia import nMedia
nMedia = nMedia(debug=False)
Content = nMedia.Content
  
class UI:
	def on_window_destroy(self, widget, data=None):
		gtk.main_quit()

	def delete_event(self, widget, event, data=None):
		gtk.main_quit()
		return False

	def __init__(self):
		builder = gtk.Builder()
		builder.add_from_file("gtk-ui.xml") 
		
		self.window = builder.get_object("window")
		self.treeview = builder.get_object("treeview")
		builder.connect_signals(self)
		
		self.window.connect("delete_event", self.delete_event)
		
		#id INTEGER NOT NULL PRIMARY KEY, 
		#		title TEXT NOT NULL,
		#		updated DATE,
				
		#		url TEXT,
		#		released DATE,
		#		rating REAL,
		#		plot_short TEXT,
		#		plot_long TEXT,
		#		ended DATE,
		#		status TEXT
		
		
		#id,title,last updated, url (SKIPPED), released, rating,
		self.treestore = gtk.TreeStore(int,str,object,object,object)
		
		self.treeview.append_column(gtk.TreeViewColumn('Id', gtk.CellRendererText(), text=0))
		self.treeview.append_column(gtk.TreeViewColumn('Name', gtk.CellRendererText(), text=1))
		
		txt = gtk.CellRendererText()
		x = gtk.TreeViewColumn('Updated', txt)
		x.set_cell_data_func(txt,self.render_dateUpdated)
		self.treeview.append_column(x)
		
		txt = gtk.CellRendererText()
		x = gtk.TreeViewColumn('Released', txt)
		x.set_cell_data_func(txt,self.render_dateReleased)
		self.treeview.append_column(x)
		
		
		txt = gtk.CellRendererText()
		x = gtk.TreeViewColumn('Rating', txt)
		x.set_cell_data_func(txt,self.render_rating)
		self.treeview.append_column(x)
		
		self.treeview.set_model(model=self.treestore)
		self.treeview.show()
		self.Refresh()
		
	def render_dateUpdated(self, column, cell, model, iter):
		x = model.get_value(iter, 2)
		cell.set_property('text', str(x))
		
	def render_dateReleased(self, column, cell, model, iter):
		cell.set_property('text', None)
		
	def render_rating(self, column, cell, model, iter):
		x = model.get_value(iter, 4)
		if (x):
			cell.set_property('text', x)

		
	def Refresh(self):
		self.treeview.set_model(model=None)
		self.treestore.clear()
		c = Content.conn.cursor()
		c.execute("select * from Content order by id")
		for row in c:
			#print row
			self.treestore.append(None,[row[0],row[1],datetime.now(),datetime.now(),row[5]])
		self.treeview.set_model(model=self.treestore)

if __name__ == "__main__":
	editor = UI()
	editor.window.show()
	gtk.main()
   
